"""
FastAPI 视频分析应用主入口文件
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn

import os
import logging
import asyncio

from app.core.config import settings
from app.api.routes import video_simple
from app.services.video_analysis import video_service

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

def create_app() -> FastAPI:
    """创建 FastAPI 应用实例"""
    app = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.DESCRIPTION,
        version=settings.VERSION,
        openapi_url=f"{settings.API_V1_STR}/openapi.json",
        docs_url="/docs" if settings.ENVIRONMENT == "development" else None,
        redoc_url="/redoc" if settings.ENVIRONMENT == "development" else None,
    )

    # CORS 中间件配置
    if settings.BACKEND_CORS_ORIGINS:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    # 创建必要的目录
    os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
    os.makedirs(settings.TEMP_DIR, exist_ok=True)

    # 挂载静态文件
    app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads")

    # 注册简化的路由
    app.include_router(video_simple.router, prefix=settings.API_V1_STR)

    @app.on_event("startup")
    async def startup_event():
        """应用启动事件 - 自动加载模型"""
        logger.info("🚀 应用启动中...")
        
        if not settings.PRELOAD_MODEL_ON_STARTUP:
            logger.info("⏭️ 模型预加载已禁用，将在首次请求时加载")
            return
        
        logger.info("🤖 正在预加载视频分析模型...")
        logger.info(f"⏱️ 启动超时设置: {settings.STARTUP_TIMEOUT}秒")
        
        try:
            # 设置超时
            success = await asyncio.wait_for(
                video_service.initialize_model(),
                timeout=settings.STARTUP_TIMEOUT
            )
            
            if success:
                logger.info("✅ 模型预加载成功！应用已就绪。")
                logger.info(f"🎯 模型设备: {video_service.device}")
                logger.info(f"💾 CUDA可用: {video_service.model is not None and hasattr(video_service, 'device') and 'cuda' in str(video_service.device)}")
            else:
                logger.warning("⚠️ 模型预加载失败，将在首次请求时重试。")
                
        except asyncio.TimeoutError:
            logger.error(f"⏰ 模型加载超时（>{settings.STARTUP_TIMEOUT}秒），将在首次请求时重试")
        except Exception as e:
            logger.error(f"❌ 模型预加载异常: {str(e)}")
            logger.warning("🔄 模型将在首次请求时加载")
    
    @app.on_event("shutdown")
    async def shutdown_event():
        """应用关闭事件"""
        logger.info("🛑 应用关闭中...")
        
        try:
            # 清理缓存
            video_service.clear_cache()
            
            # 如果有GPU，清理GPU内存
            if hasattr(video_service, 'device') and video_service.device and 'cuda' in str(video_service.device):
                try:
                    import torch
                    torch.cuda.empty_cache()
                    logger.info("🧹 GPU缓存已清理")
                except:
                    pass
                    
            logger.info("✅ 应用已安全关闭")
        except Exception as e:
            logger.error(f"❌ 关闭时出现异常: {e}")

    @app.get("/")
    async def root():
        """根路径"""
        model_status = "ready" if video_service.is_model_ready() else "loading"
        return {
            "message": "视频分析 API",
            "version": settings.VERSION,
            "model_status": model_status,
            "docs": "/docs" if settings.ENVIRONMENT == "development" else None,
        }

    @app.get("/health")
    async def health_check():
        """健康检查"""
        model_ready = video_service.is_model_ready()
        return {
            "status": "healthy" if model_ready else "initializing",
            "service": settings.PROJECT_NAME,
            "model_ready": model_ready,
            "model_status": video_service.get_initialization_status()
        }

    return app

# 创建应用实例
app = create_app()

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.ENVIRONMENT == "development",
        log_level="info",
    )